package controllers

import (
	"github.com/gin-gonic/gin"
	"my-new-gin/commonfunc"
	"my-new-gin/entitys"
	"my-new-gin/jwtauth"
	"my-new-gin/services"
	"my-new-gin/utils"
)

type HandlerUser struct {
	service services.ServiceUser
}

func (this *HandlerUser) Register(ctx *gin.Context) {
	paramsMap,err := utils.Params2Map(ctx)
	if err != nil {
		commonfunc.ReqFail(ctx,"controller error")
		return
	}
	ch, ok := utils.CheckParams([]string{"username","password"},paramsMap)
	if !ok {
		commonfunc.ReqMissParams(ctx,ch)
		return
	}
	user := &entitys.EntityUser{Username:paramsMap["username"].(string),Password:paramsMap["password"].(string)}
	err = this.service.InsertUser(user)
	if err != nil {
		commonfunc.ReqFail(ctx,err.Error())
		return
	}
	mp := make(map[string]interface{})
	mp["username"] = user.Username
	token, _ := jwtauth.CreateToken(jwtauth.Key,mp)
	ctx.Writer.Header().Set("Token",token)
	ctx.Header("Token",token)
	ctx.Set("Token",token)
	commonfunc.ReqSuccess(ctx, "success")
}

func (this *HandlerUser) Login(ctx *gin.Context) {
	paramsMap,err := utils.Params2Map(ctx)
	if err != nil {
		commonfunc.ReqFail(ctx,"controller error")
		return
	}
	ch, ok := utils.CheckParams([]string{"username","password"},paramsMap)
	if !ok {
		commonfunc.ReqMissParams(ctx,ch)
		return
	}
	uName := paramsMap["username"].(string)
	uPwd := paramsMap["password"].(string)
	user, err := this.service.SelectUserByUsernameAndPassword(uName, uPwd)
	if err != nil {
		commonfunc.ReqFail(ctx,err.Error())
		return
	}
	mp := make(map[string]interface{})
	mp["username"] = user.Username
	token, _ := jwtauth.CreateToken(jwtauth.Key,mp)
	ctx.Writer.Header().Set("Token",token)
	ctx.Header("Token",token)
	ctx.Set("Token",token)
	commonfunc.ReqSuccess(ctx, user)
}

func (this *HandlerUser) GetUserList(ctx *gin.Context) {
	paramsMap,err := utils.Params2Map(ctx)
	if err != nil {
		commonfunc.ReqFail(ctx,"controller error")
		return
	}
	u := new(entitys.EntityUser)
	_, err = utils.Map2Struct(paramsMap,u)
	if err != nil {
		commonfunc.ReqFail(ctx,"controller error")
		return
	}
	userList, err := this.service.SelectUserList(u)
	if err != nil {
		commonfunc.ReqFail(ctx,err.Error())
		return
	}
	commonfunc.ReqSuccess(ctx, userList)
}
